//
//  StrategyDetailsViewController.m
//  project
//
//  Created by 张振宇 on 15/10/27.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "StrategyDetailsViewController.h"
#import "PKRequestManager.h"
#import "StrategyDetailsModel.h"
#import "StrategyViewController.h"
#import <UIImageView+WebCache.h>
#import "UMSocial.h"
#import "FMDatabase.h"

@interface StrategyDetailsViewController ()<UIWebViewDelegate,UIScrollViewDelegate>
@property (nonatomic, strong) UIWebView *mainWebView;
@property (nonatomic, strong) UIScrollView *mainScrollView;
@property (nonatomic, strong) UIImageView *imgView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *likeBtn;
@property (nonatomic, strong) UIButton *shareBtn;
@property (nonatomic, strong) UIButton *commentBtn;
@property (nonatomic, strong) StrategyDetailsModel *model;

@property(nonatomic,strong)FMDatabase *dataBase;
@property(nonatomic,strong)NSMutableArray *array;

@end

@implementation StrategyDetailsViewController

-(NSMutableArray *)array
{
    if (_array == nil)
    {
        _array = [NSMutableArray array];
    }
    return _array;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.hidesBottomBarWhenPushed = YES;
}

- (void)requestData
{
    NSLog(@"%@",_contentId);
    NSString *btnStr = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/posts/%@",_contentId];
    [PKRequestManager requestWithTypeP:GET urlString:btnStr parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            _model = [[StrategyDetailsModel alloc]init];
            [_model setValuesForKeysWithDictionary:dic[@"data"]];
        [self reloadData];
    } error:^(NSError *error) {
        
    }];
}

- (void)reloadData
{
    [_imgView sd_setImageWithURL:[NSURL URLWithString:_model.cover_image_url]];
    UILabel *titleLbl = [[UILabel alloc]initWithFrame:CGRectMake((kWidth - 40)/2, 10, 40, 20)];
    titleLbl.text = @"攻略详情";
    titleLbl.textColor  = [UIColor whiteColor];
    self.navigationItem.titleView = titleLbl;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [_mainWebView loadHTMLString:_model.content_html baseURL:nil];
    //NSLog(@"%@",_model.content_html);
    [_likeBtn setTitle:[NSString stringWithFormat:@"%@",_model.likes_count] forState:UIControlStateNormal];
    [_shareBtn setTitle:[NSString stringWithFormat:@"%@",_model.shares_count] forState:UIControlStateNormal];
    [_commentBtn setTitle:[NSString stringWithFormat:@"%@",_model.comments_count] forState:UIControlStateNormal];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    _mainScrollView.contentSize = CGSizeMake(kWidth, 300 + [[webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"]floatValue]);
    _mainScrollView.delegate = self;
    NSLog(@"%f",webView.scrollView.contentSize.height);
    NSLog(@"====%f",[[webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"]floatValue]);
    _mainWebView.frame = CGRectMake(0, 200, kWidth, [[webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"]floatValue]+100);
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    CGFloat change = -64 -scrollView.contentOffset.y;
    if (change > 0) {
        _imgView.frame = CGRectMake(-change,-change, kWidth + change*2, 200 +change);
    }

    
}
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"%@",request);
    return YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"攻略详情";
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    _mainScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 40)];
    [self.view addSubview:_mainScrollView];
    _imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 200)];
    [_mainScrollView addSubview:_imgView];
    
    _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 150, kWidth - 20, 40)];
    _titleLabel.numberOfLines = 0;
    [_imgView addSubview:_titleLabel];
    
    _mainWebView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 200, kWidth, 1)];
    _mainWebView.delegate = self;
    [_mainScrollView addSubview:_mainWebView];
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, kHeight - 40, kWidth, 40)];
    footView.backgroundColor = [[UIColor alloc]initWithRed:221/255.0 green:160/255.0 blue:221/255.0 alpha:1];;
    [self.view addSubview:footView];
    
    _likeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _likeBtn.frame = CGRectMake(20, 10, (kWidth - 40) / 3, 20);
    [_likeBtn setImage:[UIImage imageNamed:@"shoucang"] forState:UIControlStateNormal];
    [_likeBtn addTarget:self action:@selector(like:) forControlEvents:(UIControlEventTouchUpInside)];
    [footView addSubview:_likeBtn];

    _shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _shareBtn.frame = CGRectMake(20 + (kWidth - 40) / 3, 10, (kWidth - 40) / 3, 20);
    [_shareBtn setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    [_shareBtn addTarget:self action:@selector(share:) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:_shareBtn];
    
    _commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _commentBtn.frame = CGRectMake(20 + (kWidth - 40) / 3*2, 10, (kWidth - 40) / 3, 20);
    [_commentBtn setImage:[UIImage imageNamed:@"comment"] forState:UIControlStateNormal];
    [_commentBtn addTarget:self action:@selector(didClickToComments) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:_commentBtn];
    [self requestData];
    
    NSString *filepath = [[NSSearchPathForDirectoriesInDomains(9, 1, 1)firstObject] stringByAppendingPathComponent:@"project.db"];
    _dataBase = [FMDatabase databaseWithPath:filepath];
    if ([_dataBase open])
    {
        [_dataBase executeUpdate:@"create table AllLove (loveimage text,lovetitle text, loveid text)"];
    }
    else
    {
        NSLog(@"数据库打开失败");
    }
    
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"select * from AllLove"];
    while ([resultSet next])
    {
        NSString *modelId= [resultSet stringForColumn:@"loveid"];
        [self.array addObject:modelId];
        
    }
    
    for (NSString *str in self.array)
    {
        if ([[NSString stringWithFormat:@"%@",self.contentId] isEqualToString:str])
        {
            [_likeBtn setImage:[UIImage imageNamed:@"iconfont-icon503-2"] forState:(UIControlStateNormal)];
        }
    }

    
}


-(void)like:(UIButton *)button
{
    [_array removeAllObjects];

    
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"select * from AllLove"];
    while ([resultSet next])
    {
        NSString *modelId= [resultSet stringForColumn:@"loveid"];
        [self.array addObject:modelId];
        
    }
    for (NSString *str in self.array)
    {
        if ([[NSString stringWithFormat:@"%@",self.contentId] isEqualToString:str])
        {
            [_dataBase executeUpdate:@"delete from AllLove where loveid=?", str];
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"取消收藏" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            [_likeBtn setImage:[UIImage imageNamed:@"iconfont-icon503"] forState:(UIControlStateNormal)];
            if (self.cancelBlock != nil)
            {
                 self.cancelBlock();
            }
           
            return;
        }
    }
    
    [_dataBase executeUpdate:@"insert into AllLove values (? ,?, ?)",self.model.cover_image_url,self.model.title,[NSString stringWithFormat:@"%@",self.contentId]];
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
    [_likeBtn setImage:[UIImage imageNamed:@"iconfont-icon503-2"] forState:(UIControlStateNormal)];
    
    
}


-(void)share:(UIButton *)shareButton
{
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"563b243d67e58e950e0021e0" shareText:self.model.title shareImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.model.cover_image_url]]] shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina, UMShareToDouban, UMShareToRenren,UMShareToTumblr, nil] delegate:self];
    
    



    
}

- (void)didClickToComments
{
    StrategyViewController *strategyVC = [[StrategyViewController alloc]init];
    strategyVC.contentId = _contentId;

    strategyVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:strategyVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
